package Controller;

/**
 * Controla as acoes de movimento do jogador.
 * 
 * @author Edjane Catolle, Igor Henrique, Luiz Augusto, Vladmir Chicarolli
 * @version 1.0.0
 * @since 05/31/2011
 */

import java.awt.Rectangle;
import Model.Map;
import Model.PlayerModel;

public class PlayerController extends BaseController
{	
	public PlayerController()
	{
		
	}

	@Override
	protected void ControllerHandler()
	{
		
	}

	@Override
	public void HandleKeyboard()
	{
		//37 = left arrow key
		if(GameControlsManager().GetKey() == 37)
		{
			PlayerModel.PlayerManager().MovePreviewX(-1);
			if(!GetCollision(PlayerModel.PlayerManager().GetPreviewPosition()))
			{
				PlayerModel.PlayerManager().MoveX(-1);							
			}	
		}
		
		//38 = up arrow key
		if(GameControlsManager().GetKey() == 38)
		{
			PlayerModel.PlayerManager().MovePreviewY(-1);
			if(!GetCollision(PlayerModel.PlayerManager().GetPreviewPosition()))
			{
				PlayerModel.PlayerManager().MoveY(-1);
			}	
		}
				
		//39 = right arrow key
		if(GameControlsManager().GetKey() == 39)
		{
			PlayerModel.PlayerManager().MovePreviewX(1);
			if(!GetCollision(PlayerModel.PlayerManager().GetPreviewPosition()))
			{
				PlayerModel.PlayerManager().MoveX(1);		
			}			
		}
		
		//40 = down arrow key
		if(GameControlsManager().GetKey() == 40)
		{
			PlayerModel.PlayerManager().MovePreviewY(1);
			if(!GetCollision(PlayerModel.PlayerManager().GetPreviewPosition()))
			{
				PlayerModel.PlayerManager().MoveY(1);
			}			
		}
	}
	
	/**
	 * Verifica se o jogador esta colidindo com algum tile bloqueado no cenario.
	 * @param playerRect - O Retangulo do jogador, responsavel por definir a area de colisao do jogador
	 * @return - true se o jogador esta colidindo.
	 */
	private boolean GetCollision(Rectangle playerRect)
	{
		boolean ret = false;
		
		if((playerRect.x < 0) || (playerRect.x > 950) || (playerRect.y < 0) || (playerRect.y > 650))
		{
			ret = true;		
		}
		
		if(!ret)
		{
			for (int i = 0; i < Map.getWalls().size(); i++) 
			{
				Rectangle r = Map.getWalls().get(i + 1);
				
				if(playerRect.intersects(r))
				{
					ret = true;
				}
				else
				{
					ret = false;
				}
				
				if(ret)
				{
					break;
				}			
			}
		}		
		
		return ret;
	}	
}
